<template>
  <div class="china-route" :style="{ backgroundImage: `url(${backgroundImage})` }">
    <!-- 直接使用 Sakura 组件 -->
    <Sakura :num="20" :show="true" :zIndex="9998" />
    <!-- 使用 Swiper 组件 -->
    <div class="swiper-container">
      <Swiper ref="swiper" :initial="0" :interval="3000" :auto="true">
        <Slider v-for="(item, index) in images" :key="index">
          <img :src="item" alt="Slider Image" srcset="" />
        </Slider>
      </Swiper>
    </div>

    <div class="content-wrapper">
      <img src="@/assets/LittleBoss.png" alt="Little Boss" class="little-boss-image" />
      <div class="input-container">
        <textarea class="input-box-a" v-model="responseMessage" readonly></textarea>
        <div class="input-group-b">
          <input type="text" class="input-box-b" v-model="userMessage" placeholder="请输入内容..."
            @keypress.enter="sendMessage" />
          <button class="send-button" @click="sendMessage">发送</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import backgroundImage from '@/assets/bridge_sakura.png';
import { onMounted, onUnmounted, watch, h } from 'vue';
import Sakura from '@/vuepress-plugin-sakura/bin/Sakura.vue';
import Swiper from "@/components/Swiper.vue";
import Slider from "@/components/Slider.vue";  // Import Sakura plugin

export default {
  components: {
    Slider,
    Swiper,
    Sakura,
    // Carousel, // Register Swiper
  },
  data() {
    return {
      limitTimes: -1,
      limitArray: Array(21).fill(-1),
      stop: null,
      staticx: null,
      userMessage: '',
      responseMessage: '',
      currentSlide: 0,
      images: [],
      currentArea: null,
      backgroundImage,
      totalDeltaX: 0,
      isGestureActive: false,
      img: null,
    };
  },
  async mounted() {
    console.log("Mounted hook executed");

    // this.setupCarouselEvents();

    await this.loadImages();
    window.onresize = this.handleResize;
    document.body.classList.add('china-route');

    // 添加 wheel 事件监听
    window.addEventListener('wheel', this.handleWheelEvent, { passive: false });
  },
  watch: {
    '$route.query.area': {
      handler(newArea) {
        console.log('Route area changed:', newArea);
        this.currentArea = newArea;
        this.loadImages(); // 重新加载图片
      },
      immediate: true
    },
    images(newImages) {  // 监听 images 的变化
      if (this.$refs.swiper) {
        this.$refs.swiper.childrenNode = newImages.map((image) => ({
          sty: {},
          className: '',
          default: () => h('img', { src: image }),
        }));
      }
    }
  },
  methods: {

    async loadImages() {
      try {
        const response = await fetch(
          `http://localhost:8006/api/images?area=${this.currentArea}`
        );

        if (!response.ok) {
          throw new Error("Failed to fetch images");
        }
        this.images = (await response.json()).map(image => `photo/${image}`);
        console.error("this.images", this.images);
      } catch (error) {
        console.error("Error loading images:", error);
      }
    },
    async sendMessage() {
      const message = this.userMessage.trim();
      if (!message) return;

      try {
        const response = await fetch("http://localhost:8006/ai/query", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            message: message,
            user_id: "周佳乐",
            bot_id: "default_bot",
            conversation_id: "default_conversation",
            tags: [],
          }),
        });

        const reader = response.body.getReader();
        const decoder = new TextDecoder("utf-8");
        let result = "";

        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          result += decoder.decode(value, { stream: true });
          this.responseMessage = result; // 实时更新输入框内容
        }

        this.userMessage = ""; // 清空输入框
      } catch (error) {
        console.error("Error sending message:", error);
        this.responseMessage = "发送消息时出错，请重试。";
      }
    },
    handleWheelEvent(event) {
      event.preventDefault(); // 阻止默认滚动行为

      // Start tracking on first wheel event
      if (!this.isGestureActive && Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
        this.isGestureActive = true;
        this.totalDeltaX = 0;
      }

      // Accumulate movement if gesture is active
      if (this.isGestureActive && Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
        this.totalDeltaX += event.deltaX;
      }

      // Detect gesture end (when deltaX and deltaY are both 0)
      if (this.isGestureActive && event.deltaX === 0 && event.deltaY === 0) {
        if (Math.abs(this.totalDeltaX) > 50) {
          if (this.totalDeltaX > 0) {
            this.$refs.swiper.nextSlider();
          } else {
            this.$refs.swiper.preSlider();
          }
        }
        // Reset for next gesture
        this.isGestureActive = false;
        this.totalDeltaX = 0;
      }
    },
  },
  beforeDestroy() {

    document.body.classList.remove('china-route');
    // 移除 wheel 事件监听
    window.removeEventListener('wheel', this.handleWheelEvent);
  },
  created() {
    console.log('China component created');
  },
};

</script>

<style scoped>
.china-route {
  background-size: cover;
  /* 使背景图像自适应页面大小 */
  background-position: center;
  /* 背景图像居中 */
  background-repeat: no-repeat;
  height: 100vh;
  width: 100vw;
}

.swiper-container {
  display: flex;
  /* 使用 flexbox */
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中（如果需要） */
  z-index: 9999;
  /* 确保 Swiper 在背景图上方 */
  width: 80%;
  /* 或根据需要调整宽度 */
  height: 500px;
  /* 根据需要调整高度 */
  position: relative;
  /* 确保相对定位 */
  margin: 0 auto;
  /* 自动左右边距以居中 */
}

.carousel {
  position: relative;
  width: 800px;
  height: 500px;
  margin: 0 auto;
  overflow: hidden;
}

.carousel-inner {
  display: flex;
  width: 100%;
  height: 100%;
  transition: transform 0.3s ease-in-out;
  transform: translateX(-100%);
}

.carousel-inner.no-transition {
  transition: none;
}

.carousel-item {
  flex: 0 0 100%;
  width: 100%;
  height: 100%;
  opacity: 1;
}

.carousel-item.active {
  opacity: 1;
}

.carousel-item img {
  width: 100%;
  height: 100%;
  object-fit: fill;
}

.carousel-control {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  padding: 10px 20px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  cursor: pointer;
}

.carousel-prev {
  left: 10px;
}

.carousel-next {
  right: 10px;
}

.carousel-indicators {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 10px;
  z-index: 100;
}

.indicator-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: rgba(200, 200, 200, 0.6);
  cursor: pointer;
  transition: background-color 0.3s;
}

.indicator-dot.active {
  background-color: rgba(255, 255, 255, 0.8);
}

.arrow-button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  cursor: pointer;
  padding: 15px;
  font-size: 24px;
  z-index: 100;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s;
}

.arrow-button:hover {
  background: rgba(0, 0, 0, 0.8);
}

.arrow-left {
  left: 2px;
}

.arrow-right {
  right: 2px;
}

.content-wrapper {
  display: flex;
  align-items: flex-start;
  width: 1000px;
  margin: 0 auto;
  position: relative;
}

.little-boss-image {
  width: 400px;
  height: auto;
  margin: 0;
}

.input-container {
  margin-left: 0px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
}

.input-box-a {
  width: 300px;
  min-height: 100px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 20px;
  /* 修改为圆边 */
  background-color: #f9f9f9;
  margin-bottom: 10px;
  resize: none;
  position: relative;
  /* 添加相对定位 */
}

.input-box-b {
  width: 240px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.send-button {
  padding: 10px 15px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.send-button:hover {
  background-color: #0056b3;
}

@media (max-width: 768px) {
  .carousel {
    width: 90%;
    /* 移动端调整 */
    height: 300px;
  }
}

#sakura-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: -1;
}
</style>